﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Furion.CMS.Application
{
    /// <summary>
    /// 外部事件模型
    /// </summary>
    public class OuterEventModel
    {
        /// <summary>
        /// Id
        /// </summary>
        public int? Id { get; set; }
        /// <summary>
        /// 事件名称
        /// </summary>
        public string Event { get; set; }

        private object dataObject;

        /// <summary>
        /// 数据对象
        /// </summary>
        public object DataObject
        {
            get { return this.dataObject; }
            set
            {
                this.dataObject = value;
                this.Data = JsonConvert.SerializeObject(value)
                    .Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries)
                    .ToList();
            }
        }

        /// <summary>
        /// 数据列表
        /// </summary>
        public List<string> Data { get; private set; }
        /// <summary>
        /// 注解
        /// </summary>
        public string Comment { get; set; }

        public override string ToString()
        {
            string idStart = "id:";
            string eventStart = "event:";
            string dataStart = "data:";
            string commentStart = ":";

            StringBuilder sb = new StringBuilder();

            if (Comment != null)
            {
                sb.Append(commentStart);
                sb.AppendLine(Comment);
            }

            if (Event != null)
            {
                if (Id != null)
                {
                    sb.Append(idStart);
                    sb.AppendLine(Id.Value.ToString());
                }

                sb.Append(eventStart);
                sb.AppendLine(Event);

                if (Data != null)
                {
                    foreach (string thisDatum in Data)
                    {
                        sb.Append(dataStart);
                        sb.AppendLine(thisDatum);
                    }
                }

                sb.AppendLine();
            }

            return sb.ToString();
        }

        /// <summary>
        /// 创建心跳
        /// </summary>
        /// <returns></returns>
        public static OuterEventModel CreateHeartbeat()
        {
            return new OuterEventModel { Event = "Heartbeat", Comment = $"Heartbeat {DateTime.Now:o}", DataObject = $"{DateTime.Now:yyyy-MM-dd HH:mm:ss}" };
        }
    }
}
